package poem_info;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.jdbc.core.JdbcTemplate;
import writers_info.JdbcUtils.JDBCUtils;

import java.net.URL;
import java.util.List;
import java.util.Map;

public class Id {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    private Integer id = null;
    public Integer getId(String dw, int i) {
        if(i == 1) {//1代表查询作者id
            id = getWriter_id(dw);
            if(id == null) {
                template.update("insert into writers(id, writer) values(null, ?)", dw);
                getWriterInfo(dw);
                id = getWriter_id(dw);
            }
        } else if(i == 2) {//2代表查询朝代id
            id = getDynasty_id(dw);
            if(id == null) {
                template.update("insert into dynasties(id, dynasty) values(null, ?)", dw);
                id = getDynasty_id(dw);
            }
        }
        return id;
    }

    public Integer getWriter_id(String dw) {
        String sql = "select id from writers where writer = ?";
        List<Map<String, Object>> list = template.queryForList(sql, dw);
        for (Map<String, Object> l:list) {
            id = (Integer) l.get("id");
        }
        return id;
    }

    public Integer getDynasty_id(String dw) {
        String sql = "select id from dynasties where dynasty = ?";
        List<Map<String, Object>> list = template.queryForList(sql, dw);
        for (Map<String, Object> l:list) {
            id = (Integer) l.get("id");
        }
        return id;
    }

    public void getWriterInfo(String dw) {
        try {
            String sql = "update writers set details=?, wurl=? where writer = ?";
            String wurl = "https://baike.baidu.com/item/" + dw;
            Document document = Jsoup.parse(new URL(wurl), 10000);
            Elements paras = document.select("div.lemma-summary > div.para");
            String details = "";
            for (Element para : paras) {
                details += para.text();
            }
            //保存为空的多半是百度词条不存在
            template.update(sql, details, wurl, dw);
        } catch (Exception e) {
            System.out.println(dw + "error!");
        }
    }
}
